<?php

namespace app\admin\controller\coupon;

use app\admin\model\Shop;
use app\admin\model\Shopdou;
use app\admin\model\Shopmeituan;
use app\api\service\MtUtil;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

/**
 * 店铺美团产品
 *
 * @icon fa fa-circle-o
 */
class Mt extends Backend
{

    /**
     * Mt模型对象
     * @var \app\admin\model\coupon\Mt
     */
    protected $model = null;
    protected $searchFields = 'shop.name';
    protected $appKey = "";
    protected $secret = "";
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\coupon\Mt;
        $this->appKey = "2c8bce9314172fc1";
        $this->secret = "bb39c01023ce0fbb519d2b68f4457ec37fbc0e6a";
        $this->view->assign("couponType", $this->model->getCouponType());

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['shop'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as &$m) {
                $roomList = $m['room_id'];
                $roomType = $m['type'];
                if (!empty($roomList)) {
                    $roomList = json_decode($roomList, true);
                    if ($roomType == 'qp') {
                        //查询包厢名称
                        $roomName = Db::name('shop_room')->where('id', 'in', $roomList)->field('name')->select();
                    } else {
                        //查询台桌名称
                        $roomName = Db::name('shop_table')->where('id', 'in', $roomList)->field('name')->select();
                    }
                    $roomArr = array();
                    foreach ($roomName as $n) {
                        $roomArr[] = $n['name'];
                    }
                    $m['room_name'] = $roomArr;
                } else {
                    $m['room_name'] = '';
                }

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $type = $params['type'];
        $room_id = $params['room_id'];
        $table_id = $params['table_id'];

        if($type == 'qp'){
            if(empty($room_id)){
                $this->error('包厢不能为空');
            }
            $params['room_id'] = '[' . $params['room_id'] . ']';
            unset($params['table_id']);
        }elseif ($type == 'tq'){
            if(empty($table_id)){
                $this->error('台桌不能为空');
            }
            $params['room_id'] = '[' . $params['table_id'] . ']';
            unset($params['table_id']);
        }else{
            $this->error('未知券的类型');
        }
        unset($params['title']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $this->model->where('id', $ids)->update($params);
            //$result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 一键同步
     */
    public function sync()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
    }

    public function syncCouponInfo()
    {

        $shop_id = $this->request->param('shop_id');
        $shopModel = new Shop();
        $shop = $shopModel->where('id', $shop_id)->find();
        $open_shop_uuid = $shop['open_shop_uuid'];
        $mt_update_time = $shop['mt_update_time'];
        if ($mt_update_time < time()) {
            $this->error('美团核券已过期，需要续期');
        }
        $mtUtil = new MtUtil();

        if ($shop['is_sync'] == 1) {
            $app_key = $this->appKey;
            $secret = $this->secret; //秘钥
        } else {
            $app_key = "b44cbbcb2b9ec9e9";
            $secret = "1ff99c2e910d7f52590cfc88e1aafb2add6bb2bd"; //秘钥
        }

        $sign_method = 'MD5';
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $offset = 0;
        $limit = 100;
        $url = 'https://openapi.dianping.com/tuangou/deal/queryshopdeal?';//查询券
        $data = [
            'app_key' => $app_key,
            'sign_method' => $sign_method,
            'timestamp' => $timestamp,
            'format' => $format,
            'v' => $v,
            'session' => $shop['mt_token'],
            'open_shop_uuid' => $open_shop_uuid,

        ];

        error_log("=admin=sync=data==" . json_encode($data));
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);
        $data['sign'] = $sign;
        $postdata = http_build_query($data);
        $tmpInfo = $mtUtil->curl_get($url . $postdata);

        error_log("=admin==sync=mt==" . json_encode($tmpInfo));
        Log::info("=admin==sync=mt==" . json_encode($tmpInfo));

        $shopMtModel = new Shopmeituan();

        $code = $tmpInfo['code'];
        $msg = $tmpInfo['msg'];
        if ($code == 200) {
            $list = $tmpInfo['data'];
            error_log("==admin=size==" . count($list));

            $shopMtModel->where('shop_id', $shop_id)->update(['sale_status' => 3]);

            foreach ($list as $key => $val) {
                $db = array();
                $detail = $shopMtModel->where('shop_id', $shop_id)->where('dealgroup_id', $val['dealgroup_id'])->find();
                $db['deal_id'] = $val['deal_id'];
                $db['dealgroup_id'] = $val['dealgroup_id'];
                $db['title'] = $val['title'];
                $db['shop_id'] = $shop_id;
                $db['price'] = $val['price'];
                $db['marketprice'] = $val['marketprice'];
                $db['receipt_begin_date'] = strtotime($val['receipt_begin_date']);
                $db['receipt_end_date'] = strtotime($val['receipt_end_date']);
                $db['sale_status'] = $val['sale_status'];
                $db['deal_type'] = $val['deal_type'];


                error_log($val['sale_status'] . "====dealgroup_id===" . $val['dealgroup_id']);
                if ($val['dealgroup_id'] == '844728153') {
                    error_log("===1==" . json_encode($detail));
                    error_log("===2==" . json_encode($db));

                }

                if (!$detail) {
                    $shopMtModel->insert($db);
                } else {
                    $shopMtModel->where('id', $detail['id'])->update($db);
                }
            }

            $db['code'] = 1;
            $db['msg'] = '同步成功';
            $db['data'] = [];
        } else {
            $db['code'] = 0;
            $db['msg'] = $msg;
            $db['data'] = [];
        }
        return json($db);
    }


}
